package com.yh.correct.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.yh.common.utils.IDUtils;
import com.yh.correct.model.Guardian;
import com.yh.correct.model.Page;
import com.yh.correct.model.ResultData;
import com.yh.correct.service.ICorrectedPersonService;
import com.yh.correct.service.IGuardianService;
/**
 * 工作管理模块的监护人控制层
 * @author Administrator
 */
@RestController
@RequestMapping("/guardian")
public class GuardianController {
	
	private static Logger logger = LogManager.getLogger(GuardianController.class);
	
	@Autowired
	private IGuardianService guardianService;
	@Autowired
	private ICorrectedPersonService correctedPersonService;

	@Value("${photoPath}")
	private  String dir;
	
	
	/**
	 * 增加监督人员
	 * @param guardian
	 * @return
	 */
	@RequestMapping("/add")
	public ResultData addGuardian(@Valid Guardian guardian,MultipartFile file) throws IllegalStateException, IOException{ 
		//上传文件的名字
		String oldName=file.getOriginalFilename();
		if(!"".equals(oldName)){
			//生成文件名字
			String newName=IDUtils.genImageName()+oldName.substring(oldName.lastIndexOf("."));
			//上传文件
			file.transferTo(new File(dir,newName));
			guardian.setPhoto(newName);
		}
		logger.info("增加监督人员"+guardian);
		int i=guardianService.addGuardian(guardian);
		ResultData rd=new ResultData();
		if(i>0){         
			rd.setCode(0);
			rd.setMessage("增加成功！");
		}else{
			rd.setCode(-1);
			rd.setMessage("增加失败！");
		}
		return rd;
	}
	
	
	/**
	 * 删除监督人员
	 * @param guardian
	 * @return
	 */
	@RequestMapping("/del")
	public ResultData delGuardian(Guardian guardian){ 
		logger.info("删除监督人员"+guardian);
		String oldPhoto=(String) guardianService.getGuardian(guardian).get("photo");
		int i=guardianService.delGuardian(guardian);
		if(oldPhoto!=null){
			File f=new File(dir,oldPhoto);
			if(f.exists()){
				f.delete();
			}
		}
		ResultData rd=new ResultData();
		if(i>0){
			rd.setCode(0);
			rd.setMessage("删除成功！");
		}else{
			rd.setCode(-1);
			rd.setMessage("删除失败！");
		}
		return rd;
	}
	
	
	/**
	 * 修改监督人员
	 * @param guardian
	 * @return
	 * @throws IOException 
	 * @throws IllegalStateException 
	 */
	@RequestMapping("/update")
	public ResultData updateGuardian(@Valid Guardian guardian,MultipartFile file) throws IllegalStateException, IOException{ 
		String oldPhoto=null;
		if(!"".equals(file.getOriginalFilename())){
			oldPhoto=(String) guardianService.getGuardian(guardian).get("photo");
			//上传文件的名字
			String oldName=file.getOriginalFilename();
			//生成文件名字
			String newName=IDUtils.genImageName()+oldName.substring(oldName.lastIndexOf("."));
			//上传文件
			file.transferTo(new File(dir,newName));
			guardian.setPhoto(newName);
		}
		logger.info("修改监督人员"+guardian);
		int i=guardianService.updateGuardian(guardian);
		if(oldPhoto!=null){
			File f=new File(dir,oldPhoto);
			if(f.exists()){
				f.delete();
			}
		}
		ResultData rd=new ResultData();
		if(i>0){
			rd.setCode(0);
			rd.setMessage("修改成功！");
		}else{
			rd.setCode(-1);
			rd.setMessage("修改失败！");
		}
		return rd;
	}
	
	
	/**
	 * 查询监督人员
	 * @param guardian
	 * @return
	 */
	@RequestMapping("/get")
	public ModelAndView getGuardian(Guardian guardian){ 
		logger.info("查询监督人员"+guardian);
		Map<String,Object> map=guardianService.getGuardian(guardian);
		return new ModelAndView("work-manage/guardian_edit",map);
	}
	
	/**
	 * 模糊查询监督人员
	 * @param pageSize
	 * @param pageNum
	 * @param guardian
	 * @return
	 */
	@RequestMapping("/querylike")
	public ResultData queryLikeGuardians(Integer pageSize, Integer pageNum,Guardian guardian){ 
		logger.info("监督人员查询条件"+guardian);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("pageSize", pageSize);
		map.put("pageNum", pageNum);
		map.put("guardian",guardian);
		Page page=guardianService.queryLikeGuardians(map);
		List<Object> list=new ArrayList<Object>();
		list.add(page);
		ResultData rd=new ResultData();
		rd.setCode(0);
		rd.setMessage("查询成功！");
		rd.setData(list);
		return rd;
	}
	
	/**
	 * 查询所有矫正人员
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/queryAll")
	public ResultData queryAllCorrectedPerson() throws Exception{ 
		logger.info("查询所有矫正人员");
		List<Map<String, Object>> list=correctedPersonService.getAllCorrectedPerson();
		ResultData rd=new ResultData();
		rd.setCode(0);
		rd.setMessage("查询成功！");
		rd.setData(list);
		return rd;
	}
	
	

	
	/**
	 * 根据矫正人员查询其司法所或根据司法所查询所有矫正人员
	 * @param jdId
	 * @param cpId
	 * @return
	 */
	@RequestMapping("/getAll")
	public ResultData getCorrectedPersonAll(Integer jdId,Integer cpId){
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("jdId", jdId);
		map.put("cpId", cpId);
		List<Object> list=guardianService.getCorrectedPersonAll(map);
		ResultData rd=new ResultData();
		rd.setCode(0);
		rd.setMessage("查询成功！");
		rd.setData(list);
		return rd;
	}
	
	
	
	/**
	 * 返回页面通用方法
	 * @param page
	 * @return
	 */
	@RequestMapping("/page")
	public ModelAndView page(String page){
		return new ModelAndView(page);
	}
	
	/**
	 * 导出监护人员
	 * @param guardian
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("/export")
	public void exportPersonnels(Guardian guardian,HttpServletResponse response) throws IOException{ 
		logger.info("导出匹配的监护人员"+guardian);
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("guardian",guardian);
		Workbook wb=guardianService.exportGuardians(map);
        response.setContentType("application/vnd.ms-excel;charset=utf-8");  
        String excelName = "监护人员";  
        response.setHeader("Content-Disposition","attachment; filename="+new String(excelName.getBytes("utf-8"), "ISO8859-1" )+".xls");  
		wb.write(response.getOutputStream());
	}
}
